#include "dataProxyCommunicator.hh"
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <iostream> //tmp
#include <sstream>
#include <stdlib.h>

using namespace std;

dataProxyCommunicator::dataProxyCommunicator(int p){
    port = p;
    grid =false;
}
dataProxyCommunicator::dataProxyCommunicator(int p,  vector<string>& sites, char* dir){

    port = p;
    grid5kSites = sites;
    gridOutputDir = dir;
    grid = true;

}
e_status dataProxyCommunicator::runDataProxyServer(){

    return runServerAndConnect("decoder", port, &sock, &connected);

}

e_status dataProxyCommunicator::checkTerminate(){
     // Set non-blocking mode
     e_status r = readChar(connected, '$');

     if(r ==  SUCCESS)
          cout << "[data-proxy communicator] received termination command from decoder!" <<endl;
     else if (r == DISCONNECTED)
         cout << "[data-proxy communicator] error decoder disconnected!!" << endl;

     return r;
}

e_status dataProxyCommunicator::writeToDecoder(char* res, fixedBitSizeInteger prime){

    stringstream send_data;

    send_data << "r,"<< res << ',' << prime << '|';
        
    if (send(connected, send_data.str().c_str(),send_data.str().length(), 0) == -1)
    {
        perror("[data-proxy communicator]");
        return ERROR;
    }

    return SUCCESS;

}

e_status dataProxyCommunicator::writeRowDataToDecoder(string data){

    cout << "[data-proxy communicator] sending: "<< data <<endl;
    if (send(connected, data.c_str(),data.length(), 0) == -1)
    {
        perror("[data-proxy communicator]");
        return ERROR;
    }

    return SUCCESS;

}
e_status dataProxyCommunicator::terminate(){
    e_status res = SUCCESS;
    if (terminateSocket(connected)== ERROR)
        res = ERROR;
    if (terminateSocket(sock)== ERROR)
        res = ERROR;
    
}

void dataProxyCommunicator::syncDir(){ //
    stringstream tmp;
    for(int i = 0; i < grid5kSites.size();i++){
        tmp << "rsync -avz " << grid5kSites[i] << ':' << gridOutputDir << ' ' << gridOutputDir << " &";
        system(tmp.str().c_str());
        tmp.str("");
    }
}
void dataProxyCommunicator::createAllDirs(){
                    
    stringstream tmp;
    for(int i = 0; i < grid5kSites.size();i++){
        tmp << "ssh " << grid5kSites[i] << " 'mkdir " << gridOutputDir << "' &";
        system(tmp.str().c_str());
        tmp.str("");
    }
                    
}
void dataProxyCommunicator::deleteAllDirs(){

    stringstream tmp;
    for(int i = 0; i < grid5kSites.size();i++){
        tmp << "ssh " << grid5kSites[i] << " 'rm -rf " << gridOutputDir << "' &";
        system(tmp.str().c_str());
        tmp.str("");
    }
}

